package com.eastfair.auth.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
//import com.baomidou.dynamic.datasource.annotation.DS;
import com.eastfair.auth.enumeration.OrganizationOrgTypeEnum;
import com.eastfair.auth.service.*;
import com.eastfair.auth.dto.OrganizationDTO;
import com.eastfair.auth.entity.Organization;
import com.eastfair.auth.util.DataIsoLotionUtil;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 项目组织业务实现类
 *
 * </p>
 *
 * @author ligang
 * @date 2021-07-16
 */
@Slf4j
@Service
//@Transactional
//@DS("#thread.tenant")
public class ProjectOrganizationServiceImpl implements ProjectOrganizationService {
    @Autowired
    OrganizationService organizationService;
    @Autowired
    ResourceOrganizationService resourceOrganizationService;

    @Override
    public R<Organization> createProject(OrganizationDTO organizationDTO) {
        //校验已经是否存在
//        Organization organizationClassify = organizationService.queryOrgOfType(organizationDTO.getProjectId(), OrganizationOrgTypeEnum.P, null);
//        if (organizationClassify != null) {
//            //存在则直接返回
//            return R.success(organizationClassify);
//        }
        //切换子系统id
//        ContextUtil.setSubSystemId(DataIsoLotionUtil.findSubSystemId(organizationDTO.getSubsystemList(), OrganizationOrgTypeEnum.P.getCode()));
//        organizationDTO.setOrgType(OrganizationOrgTypeEnum.P);
//        R<Organization> r = organizationService.createOrg(organizationDTO);
//        Organization organization = r.getData();
        //初始化子系统
        List<Organization> organizationList = organizationService.initOrgAndRole(organizationDTO);
        if(CollectionUtil.isNotEmpty(organizationList)){
            return R.success(organizationList.get(0));
        }
        return R.fail("失败");
    }

    @Override
    public R<Organization> updProject(OrganizationDTO organizationDTO) {
        log.info(JSONObject.toJSONString(organizationDTO));
        //校验已经是否存在
        Organization organizationClassify = organizationService.queryOrgOfType(OrganizationOrgTypeEnum.P, null);
        if (organizationClassify != null) {
            //修改节点名字
            organizationClassify.setName(organizationDTO.getName());
            organizationService.updateById(organizationClassify);
            //存在则直接返回
            return R.success(organizationClassify);
        }
        return R.success(null);
    }

    @Override
    public R delProject(Long projectOrgId) {
        return organizationService.del(projectOrgId);
    }


}
